package com.rec.smile.rpc.consumer;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;

import com.rec.smile.rpc.api.RpcRequest;
import com.rec.smile.rpc.registry.ServiceRegistryApi;

public class JdkRpcProxy {

	private ServiceRegistryApi serviceDiscovery;
	
	public JdkRpcProxy(ServiceRegistryApi serviceDiscovery) {
		super();
		this.serviceDiscovery = serviceDiscovery;
	}


	@SuppressWarnings("unchecked")
	public <T> T create(final Class<T> interfaceClass){
		return (T)Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[]{interfaceClass}, new InvocationHandler() {
			
			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				
				RpcRequest request = new RpcRequest();
				request.setRequestId(UUID.randomUUID().toString());
//				request.setClassName(method.getDeclaringClass().getName());
				request.setClassName(interfaceClass.getName());
				request.setMethodName(method.getName());
				request.setParameterTypes(method.getParameterTypes());
				request.setParameters(args);
				
				
				if(serviceDiscovery != null){
					String serverAddress = serviceDiscovery.discover();
					return new RpcClient(serverAddress).send(request).getResult();
				}
				return null;
				
			}
		});
	}
}
